package com.firewolf.fr.servlet;

import java.io.IOException;
import java.io.Writer;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;


@WebServlet(name="index1",urlPatterns="/index1")
public class IndexServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	Configuration cfg = null;

	@Override
	public void init() throws ServletException {
		cfg = new Configuration(Configuration.VERSION_2_3_23);
		cfg.setServletContextForTemplateLoading(getServletContext(), "WEB-INF/ftl");
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Template template = cfg.getTemplate("index.ftl");
		response.setCharacterEncoding("UTF-8");
		Writer w = response.getWriter();

		Map<String, Object> model = new HashMap<String, Object>();
		model.put("user", "用户11");
		model.put("users", Arrays.asList("张三", "李四", "王五"));
		try {
			template.process(model, w);
		} catch (TemplateException e) {
			e.printStackTrace();
		}

//		try{
//			throw new ServletException();
//		}catch(ServletException e){
//			response.setHeader("Content-type", "text/html; charset=UTF-8");
//			response.setCharacterEncoding("UTF-8");
//			Writer w = response.getWriter();
//			w.write("错了，稍后重试");
//			w.flush();
////			response.sendRedirect("erro.jsp");
//		}
//	}
	}
}
